import './style.css';
import { uuid,sleep,queryPath } from '../../utils'
import tpl from './tpl.js'
import config from '../../../mp.config.js'
import { AppManager } from '../appManager'
import { downFile,readConfigFile,mergePageConfig } from './utils'
import { Bridge } from '../bridge';
import { JSCore } from '../jscore';
import sysapi from '../sysapi'


//小程序容器类
export class MiniAppSandbox {
    constructor(opts) {
		this.appInfo = opts;
		this.id = `ui_view${uuid()}`;
		this.parent = null;
		this.appConfig=null;
		this.webviewsContainer=null;
		this.webviewAnimaEnd = true;
		this.el = document.createElement('div');
		this.el.classList.add('wx-native-view');
        this.tpl=tpl;

		//通讯桥列表
		this.bridgeList = [];
		this.bridges = {};
		//逻辑线程
		this.jscore = new JSCore();
		this.jscore.parent = this;
		this.jscore.addEventListener('message', this.jscoreMessageHandler.bind(this));

		/*
			this.appId = opts.appId;
		*/

    }

	viewDidLoad() {
		this.initPageFrame();
		this.webviewsContainer=this.el.querySelector(".mini-app__webviews")
        this.showLaunchScreen();
        this.bindMinimizeEvent();
        this.bindCloseEvent();
        //初始化app
        this.initApp();
	}

    async initApp(){
		//初始化逻辑线程jscore
		await this.jscore.init();

        //1.拉取小程序资源,开者工具中拉取本地文件
		if(config.platform=='app'){
			await downFile(this.appInfo.appId);
		}

		/* 
        //1.1模拟拉取小程序资源
		await sleep(1000);
 */
        //2.读取配置文件
        /* const configPath=this.appInfo.appId+'/config.json';
        const configContent=await readFile(configPath);*/

		const configContent=await readConfigFile(this.appInfo.currProjectPath,this.appInfo.appId);
		/* const configContent=`{
			"app": {
				"entryPagePath": "pages/index/index",
				"pages": [
					"pages/index/index"
				],
				"window": {
					"navigationStyle": "custom",
					"backgroundColor": "#000000"
				},
				"networkTimeout": {},"debug": true
			},
			"modules": {
				"pages/index/index": {
					"navigationBarTextStyle": "block",
					"backgroundColor": "#000",
					"usingComponents": {}
				}
			}
		}` */
		this.appConfig=JSON.parse(configContent);

        //3.设置导航栏的颜色模式
		// const entryPagePath=this.appInfo.pagePath || this.appConfig.app.entryPagePath;
		const entryPagePath=this.appInfo.pagePath || this.appConfig.app.pages[0];
        this.updateNavigationColorStyle(entryPagePath);

        //4.创建通信桥 bridge
		const pageConfig=this.appConfig.modules[entryPagePath]//获取页面的配置
		const entryPageBridge=await this.createBridge({
			pagePath:entryPagePath,
			query:this.appInfo.query,
			scene:this.appInfo.scene,
			jscore:this.jscore,
			isRoot:true,//首页没有返回按钮
			appId:this.appInfo.appId,
			pages:this.appConfig.app.pages,
			//configInfo页面配置
			configInfo:mergePageConfig(this.appConfig.app,pageConfig),
			//如果是在开发者工具中，传当前的项目路径
			currProjectPath:this.appInfo.currProjectPath,
			windowWidth:this.appInfo.windowWidth,
			windowHeight:this.appInfo.windowHeight,
			statusBarHeight:55,//状态栏高度
		});
		this.bridgeList.push(entryPageBridge);

		entryPageBridge.start();//启动首页

        //5.触发应用的初始化逻辑
        //6隐藏启动动画
        this.hideLaunchScreen();
    }

	// 生命周期函数，监听页面加载
	onPresentIn() {
		const currentBridge = this.bridgeList[this.bridgeList.length - 1];
		//热更新后调用页面中的app.js中的onShow
		currentBridge && currentBridge.appShow();
		//调用页面中的onShow
		currentBridge && currentBridge.pageShow();
	}
	// 生命周期函数，监听页面卸载
	onPresentOut() {
		const currentBridge = this.bridgeList[this.bridgeList.length - 1];
		//热更新后调用页面中的app.js中的onHide
		currentBridge && currentBridge.appHide();
		currentBridge && currentBridge.pageHide();//调用页面中的onHide
	}
    //页面
	initPageFrame() {
		this.el.innerHTML=this.tpl
	}
	// 显示启动loading页面
	showLaunchScreen() {
		const launchScreen = this.el.querySelector('.mini-app__launch-screen');
		const name = this.el.querySelector('.mini-app__name');
		const logo = this.el.querySelector('.mini-app__logo-img-url');

		this.updateActionColorStyle('black');
		name.innerHTML = this.appInfo.appName;
		logo.src = this.appInfo.logo;
		launchScreen.style.display = 'block';
	}
    hideLaunchScreen(){
        
		const startPage = this.el.querySelector('.mini-app__launch-screen');
		startPage.style.display='none';
    }

	//设置导航栏的颜色模式
	updateNavigationColorStyle(pagePath){
		//获取页面配置中的导航栏颜色
		const pageConfig = this.appConfig.modules[pagePath];
		const mergeConfig=mergePageConfig(this.appConfig.app, pageConfig);

		this.updateActionColorStyle(mergeConfig.navigationBarTextStyle);
	}
    // 更新头部bar颜色
	updateActionColorStyle(color) {

		// 修改胶囊的颜色
		const action = this.el.querySelector('.mini-app-navigation');
		if (color === 'white') {
			action.classList.remove('wx-mini-app-navigation__actions--black');
			action.classList.add('wx-mini-app-navigation__actions--white');
		}

		if (color === 'black') {
			action.classList.remove('wx-mini-app-navigation__actions--white');
			action.classList.add('wx-mini-app-navigation__actions--black');
		}
		//修改导航栏的颜色模式
		// this.parent.updateStatusBarColor(color);
	}

    //最小化小程序
	bindMinimizeEvent() {
		const minimizeBtn = this.el.querySelector('.wx-mini-app-navigation__actions-variable');

		minimizeBtn.onclick = () => {
			AppManager.minimizeApp(this);
		};
	}

    //关闭小程序
	bindCloseEvent() {
		const closeBtn = this.el.querySelector('.wx-mini-app-navigation__actions-close');

		closeBtn.onclick = () => {
			AppManager.closeApp(this);
		};
	}

	//创建通信桥bridge对象
	async createBridge(opts){

		const {jscore,isRoot,configInfo,appId,pagePath,query,scene,pages,currProjectPath,windowWidth,windowHeight,statusBarHeight}=opts
		const bridge=new Bridge({jscore,isRoot,configInfo,appId,pagePath,query,scene,pages,currProjectPath,windowWidth,windowHeight,statusBarHeight});
		bridge.parent=this;//bridge.parent指向miniAppSandbox对象
		await bridge.init();
		return bridge;
	}

	jscoreMessageHandler(msg){

		const {type,body}=msg;
		if(type!=='trrigerWXApi'){
			return false;
		}
		const {apiName,params}=body;
		this[apiName](params);
	}
	createCallBack(callbackId){
		const self=this;
	    return function(...arges){
			self.jscore.postMessage({
				type:'trrigerCallback',
				body:{
					callbackId,
					arges
				}
			})
		}
	}
	navigateTo(opts){
		const {url,success}=opts;
		const {query,pagePath}=queryPath(url);
		const successCallback=this.createCallBack(success);
		this.openPage({
			pagePath:pagePath.replace(/^\//,''),
			query,
			onSuccess:successCallback
		});
	}
	async navigateBack(opts){
		if (this.bridgeList.length < 2) {
			return;
		}

		if (!this.webviewAnimaEnd) {
			return;
		}

		this.webviewAnimaEnd = false;

		const currentBridge = this.bridgeList.pop();
		const preBridge = this.bridgeList[this.bridgeList.length - 1];

		// 更新状态栏颜色模式
		this.updateTargetPageColorStyle(preBridge.opts.pagePath);

		// 当前页面推出
		currentBridge.webview.el.classList.add('wx-native-view--before-enter');
		currentBridge.webview.el.classList.add('wx-native-view--enter-anima');

		// 触发当前页面的生命周期函数
		currentBridge.destroy && currentBridge.destroy();

		// 上一个页面推入
		preBridge.webview.el.classList.remove('wx-native-view--slide-out');
		preBridge.webview.el.classList.add('wx-native-view--instage');
		preBridge.webview.el.classList.add('wx-native-view--enter-anima');

		// 触发上一个页面的生命周期函数
		preBridge.pageShow && preBridge.pageShow();
		await sleep(540);
		this.webviewAnimaEnd = true;

		// 页面进入后移出动画相关class
		preBridge.webview.el.classList.remove('wx-native-view--enter-anima');
		preBridge.webview.el.classList.remove('wx-native-view--instage');
		currentBridge.webview.el.parentNode.removeChild(currentBridge.webview.el);
	}
	navigateToMiniProgram(opts){
		const {appId,path}=opts;
		AppManager.openApp({
			appId,
			path,
			scene:1037
		},this.parent)
	}
	async openPage(opts){
	    if(!this.webviewAnimaEnd){
			return false;
		}
		this.webviewAnimaEnd=false;
		const {pagePath,query,onSuccess}=opts;

		this.updateTargetPageColorStyle(pagePath);

		const pageConfig=this.appConfig.modules[pagePath];

		const bridge=await this.createBridge({
			pagePath,
			query,
			scene:this.appInfo.scene,
			jscore:this.jscore,
			isRoot:false,
			appId:this.appInfo.appId,
			pages:this.appConfig.app.pages,
			configInfo:mergePageConfig(this.appConfig.app, pageConfig),
			//如果是在开发者工具中，传当前的项目路径
			currProjectPath:this.appInfo.currProjectPath,
			windowWidth:this.appInfo.windowWidth,
			windowHeight:this.appInfo.windowHeight,
			statusBarHeight:55,//状态栏高度
		});

		const preBridge=this.bridgeList[this.bridgeList.length-1];
		const preWebview=preBridge.webview;

		this.bridgeList.push(bridge);

		this.bridges[bridge.id]=bridge;

		bridge.start(false);
		// 上一个页面推出
		preWebview.el.classList.remove('wx-native-view--instage');
		preWebview.el.classList.add('wx-native-view--slide-out');
		preWebview.el.classList.add('wx-native-view--linear-anima');
		preBridge.pageHide && preBridge.pageHide();

		// 新页面推入
		bridge.webview.el.style.zIndex = this.bridgeList.length + 1;
		bridge.webview.el.classList.add('wx-native-view--enter-anima');
		bridge.webview.el.classList.add('wx-native-view--instage');
		await sleep(540);

		// 页面进入后移出动画相关class
		this.webviewAnimaEnd = true;
		preWebview.el.classList.remove('wx-native-view--linear-anima');
		bridge.webview.el.classList.remove('wx-native-view--before-enter');
		bridge.webview.el.classList.remove('wx-native-view--enter-anima');
		bridge.webview.el.classList.remove('wx-native-view--instage');
		onSuccess && onSuccess();
	}
	// 设置指定页面状态栏的颜色模式
	updateTargetPageColorStyle(pagePath) {
		/* if (!pagePath) {
			this.updateActionColorStyle('black');
			return;
		}
		
		const pageConfig = this.appConfig.modules[pagePath];
		const mergeConfig = mergePageConfig(this.appConfig.app, pageConfig);
		const { navigationBarTextStyle } = mergeConfig;

		this.updateActionColorStyle(navigationBarTextStyle); */
	}
	chooseMessageFile(opts){
		sysapi.chooseMessageFile(opts);
	}
	setStorage(opts){
		sysapi.setStorage(opts.key,opts.value);
	}
	getStorage(opts){
		sysapi.getStorage(opts.key,(result)=>{
			this.jscore.postMessage({
				type:'getStorage',
				body:{
					data:result
				}
			})
		});
	}
	removeStorage(opts){
		sysapi.removeStorage(opts.key,(result)=>{
			this.jscore.postMessage({
				type:'removeStorage',
				body:{
					data:result
				}
			})
		});
	}
	clearStorage(opts){
		sysapi.clearStorage((result)=>{
			this.jscore.postMessage({
				type:'clearStorage',
				body:{
					data:result
				}
			})
		});
	}
	setNavigationBarTitle(opts){
		const {title,success}=opts;
		const successCallback=this.createCallBack(success);
		const pageName=this.el.querySelector('.wx-native-webview__navigation-title');
		pageName.innerText=title;
		successCallback || successCallback()
	}
    //设置系统剪贴板的内容
	setClipboardData(opts){
		sysapi.setClipboardData(opts,(result)=>{
			this.jscore.postMessage({
				type:'setClipboardData',
				body:{
					data:result
				}
			})
		});
	}
    //获取系统剪贴板的内容
	getClipboardData(opts){
		sysapi.getClipboardData(opts,(result)=>{
			this.jscore.postMessage({
				type:'getClipboardData',
				body:{
					data:result
				}
			})
		});
	}
    //打开外部文件
	openExternalFile(opts){
		sysapi.openExternalFile(opts,(result)=>{
			this.jscore.postMessage({
				type:'openExternalFile',
				body:{
					data:result
				}
			})
		});
	}
}